#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"

#define TASK_STACK_SIZE         (1024*2)                //任务栈大小
#define TASK_PRIO               (20) 
#define KEY                     (34)
#define LED1                    (5)
#define LED2                    (2)
#define MAX_COUNT               (100)

static int g_flag = 0;
int g_count = 0;
int g_gpio_init_flag = 0;

GpioIsrCallbackFunc KeyIntFunc(void)
{
    g_flag = 1;
    
}

static void KeyledTestTask(void)
{
    int temp = 0;
    IoTGpioInit(KEY);
    IoTGpioInit(LED1);
    IoTGpioInit(LED2);

    IoTGpioSetDir(KEY, IOT_GPIO_DIR_IN);
    // IoTGpioSetDir(34, IOT_GPIO_DIR_IN);
    IoTGpioSetDir(LED1, IOT_GPIO_DIR_OUT);
    IoTGpioSetDir(LED2, IOT_GPIO_DIR_OUT);
    osDelay(100);
    IoTGpioRegisterIsrFunc(KEY, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, KeyIntFunc, NULL);  //设置KEY为低电平中断触发

    while(1){
        if(1 == g_flag){
            temp = !temp;
            IoTGpioSetOutputVal(LED1, !temp);
            IoTGpioSetOutputVal(LED2, temp);
            // IoTGpioGetInputVal(34, &vin);
            g_count++;
            osDelay(300);
            g_flag=0;
            printf("LED1 is %d,\tLED2 is %d,\tcount = %d\r\n", !temp, temp, g_count);
        }
        osDelay(100);
    }
    printf("end\r\n");
    IoTGpioDeinit(KEY);
    IoTGpioDeinit(LED1);
    IoTGpioDeinit(LED2);
    g_gpio_init_flag = 0;
    osThreadExit();
}

void EthernetDemo(void)
{
    osThreadAttr_t attr;

    attr.name = "TASK_NAME";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)KeyledTestTask, NULL, &attr) == NULL) {
        printf("Failed to create thread!\n");
    }
}

APP_FEATURE_INIT(EthernetDemo);